﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace bmapi.Controllers
{
    public class cadDownloadController : CADController
    {
        [HttpGet,Route("cadDownload/Download")]
        public int Download(string id)
        {
            int result = 0;      

            string url = id.Replace('!', '%');
            //前面12位是时间,用于控制下载本地缓冲区内的数据,还是下载服务器上的数据
            string s = HttpUtility.UrlDecode(url.Substring(12), System.Text.Encoding.UTF8);
            string path = System.Web.Hosting.HostingEnvironment.MapPath("/BuyiRoot");

            HttpContext context = HttpContext.Current;
            FileInfo DownloadFile = null;
            try
            {
                DownloadFile = new FileInfo(path + "\\" + s);
                long sss = DownloadFile.Length;

                if (File.Exists(DownloadFile.FullName))
                    result = 1;
                else
                    result = 0;                
            }
            catch (Exception)
            {
                result = 0;
            }
            try
            {

                if (result == 1)
                {
                   context.Response.Clear();
                    context.Response.ClearHeaders();
                    context.Response.Buffer = false;
                    context.Response.ContentType = "application/octet-stream";
                    context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.Name, System.Text.Encoding.UTF8));
                    context.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
                    context.Response.WriteFile(DownloadFile.FullName);
                    context.Response.Flush();

                    //WriteDebug("cadDownload/Download", DownloadFile.FullName);
                }
                else
                {
                    context.Response.Clear();
                    context.Response.ClearHeaders();
                    context.Response.Buffer = false;
                    context.Response.ContentType = "application/octet-stream";
                    context.Response.AppendHeader("Content-Disposition", "attachment;filename=");
                    context.Response.AppendHeader("Content-Length", "0");
                    context.Response.Flush();

                    //WriteDebug("cadDownload/Download 失败", s);
                }
            }
            catch (Exception e)
            {
                WriteDebug("cadDownload/Download 失败", e.Message);
                result = 0;
            }
            finally
            {
                context.Response.End();
            }
            return result;
        }

    }
}
